<template>
  <div class="app-container">
    <el-row type="flex" class="row-bg btn-row" justify="end">
      <el-button class="filter-item" size="mini" v-if="$store.state.user.user_perms.includes('1007')" @click="exportData" type="primary" icon="el-icon-plus">{{$t('colTransaction.download')}}</el-button>
    </el-row>
    <el-collapse>
      <el-collapse-item>
        <div slot="title">
          &nbsp;&nbsp;&nbsp;{{$t('pmTransaction.click_filter')}}&nbsp;&nbsp;&nbsp;<i class="icon iconfont icon-filter" style="font-size: 10px"></i>
        </div>
        <el-form :inline="true" :model="q" class="demo-form-inline query" label-position="left" >
          <el-row >             
              <div class="col-container">
                  <span class="searchlabel">{{$t('pmTransaction.bankcard_name')}}</span>
              </div>   
              <div class="input-container-left">
                 <el-input v-model="q.bankcard_name" :placeholder="$t('pmTransaction.bankcard_name')" prefix-icon="el-icon-edit"></el-input>
              </div>   
               <div class="col-container">
                  <span class="searchlabel">{{$t('pmTransaction.account_details')}}</span>
              </div>   
              <div class="input-container-left">
                 <el-input v-model="account_details" :placeholder="$t('pmTransaction.account_details')" prefix-icon="el-icon-edit"></el-input>
              </div>           
              <div class="col-container">
                  <span class="searchlabel">{{$t('colTransaction.details')}}</span>
              </div>
              <div class="input-container-left">
                 <el-input v-model="q.notes" :placeholder="$t('pmTransaction.details')" prefix-icon="el-icon-edit"></el-input>
              </div>
              <div class="col-container">
                    <span class="searchlabel">{{$t('pmTransaction.bank')}}</span>
              </div>    
              <div class="input-container-left">
                 <el-input v-model="q.bank" :placeholder="$t('pmTransaction.bank')" prefix-icon="el-icon-edit"></el-input>
              </div>
          </el-row>  
          <br>
          <el-row >             
              <div class="col-container">
                  <span class="searchlabel">{{$t('pmTransaction.type')}}</span>
              </div>   
              <div class="input-container-left">
                <el-select v-model="q.type" :placeholder="$t('pmTransaction.type')" prefix-icon="el-icon-edit">
                  <el-option :label="$t('pmTransaction.all')" value=""></el-option>
                  <el-option v-for="(item, key) of types" :key="key" :label="getTypew(key)" :value="parseInt(key)"></el-option>
                </el-select>
              </div>  
              <div class="col-container">
                  <span class="searchlabel">{{$t('pmTransaction.amount')}}</span>
              </div>   
              <div class="input-container-left">
                  <el-input v-model="q.amount" :placeholder="$t('pmTransaction.amount')" prefix-icon="el-icon-edit"></el-input>
              </div>   
               <div class="col-container">
                  <span class="searchlabel">{{$t('pmTransaction.balance')}}</span>
              </div>   
              <div class="input-container-left">
                 <el-input v-model="q.balance" :placeholder="$t('pmTransaction.balance')" prefix-icon="el-icon-edit"></el-input>
              </div>
               <div class="col-container">
                  <span class="searchlabel">{{$t('pmTransaction.merchant')}}</span>
              </div>   
              <div class="input-container-left">
                <el-select v-model="q.mch_id" :placeholder="$t('orderWithdraw.select')">
                  <el-option :label="$t('orderWithdraw.all')" :value=null></el-option>
                  <el-option v-for="mch of MchList" :key="mch.id" :label="mch.name" :value="mch.id"></el-option>
                </el-select>                 
              </div>
          </el-row> 
          <br />
          <el-row >
            <div class="col-container">
              <span class="searchlabel">{{$t('pmTransaction.transaction_time')}}</span>
            </div>    
            <div class="input-container-left">
              <el-date-picker v-model="q.transaction_time.$gte" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" :placeholder="$t('pmTransaction.select_datetime')"></el-date-picker>
            </div>
            <span>-</span>
            <div class="input-container-right">
              <el-date-picker v-model="q.transaction_time.$lt" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" :placeholder="$t('pmTransaction.select_datetime')"></el-date-picker>
            </div>        
          </el-row>
          <br />
          <el-row> 
              <div style="float:right; margin-right:30px;">
                <el-button type="primary" @click="query">{{$t('pmTransaction.search')}}</el-button>
                <el-button type="danger" @click="reload">{{$t('pmTransaction.reset')}}</el-button>
              </div>
          </el-row>           
        </el-form>        
      </el-collapse-item>
    </el-collapse>
    <br>
    <el-row>
        <!-- 总收入: <span style="color: #f00;line-height: 80px" v-if="listData.income">{{listData.income.toFixed(2)}}</span>元&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; -->        
        <div class="col-container">
          <span class="searchlabel">{{$t('pmTransaction.total_income')}}</span> 
        </div>    
        <div class="input-container-left"><span style="color: #f00;line-height: 80px; font-weight:600">{{this.totalDeposit}}</span>{{$t('pmTransaction.currency')}}</div>
        <div class="col-container" style="margin-left:-40px">
          <span class="searchlabel">
          {{$t('pmTransaction.total_expenses')}} 
          </span>
        </div> 
        <div class="input-container-left">
          <span style="color: #f00;line-height: 80px; font-weight:600">{{this.totalExpenses}}</span>{{$t('pmTransaction.currency')}}
        </div>
    </el-row>
    <el-table :data="listData.list" v-loading.body="listLoading" @sort-change="sortlist" element-loading-text="Loading" stripe border fit> 
      <el-table-column prop="bankcard_name" :label="$t('pmTransaction.bankcard_name')" sortable width="125"></el-table-column>
      <el-table-column prop="type" :label="$t('pmTransaction.type')" width="180">
        <template slot-scope="scope">{{ getTypew(scope.row.type)}}</template>      
      </el-table-column>   
      <el-table-column prop="bank" :label="$t('pmTransaction.bank')" sortable width="110"></el-table-column>
      <el-table-column prop="mch_id" :label="$t('pmTransaction.merchant')" sortable width="110"></el-table-column>
      <el-table-column prop="order_id" :label="$t('pmTransaction.order_id')" sortable width="120"></el-table-column>
        <el-table-column prop="details" :label="$t('pmTransaction.account_details')" sortable width="250">
          <template slot-scope="scope">{{getAccountDetails(scope.row)}}</template>      
      </el-table-column>
      <el-table-column prop="infodetails" :label="$t('pmTransaction.details')" sortable width="200">
        <template slot-scope="scope">{{scope.row.notes}} </template>
      </el-table-column>
      <el-table-column prop="trading_channel" :label="$t('pmTransaction.channel')" sortable width="200"></el-table-column>
        <el-table-column prop="pay_amount" :label="$t('colTransaction.pay_amount')" sortable width="170">
        </el-table-column>
        <el-table-column prop="withdraw_amount" :label="$t('colTransaction.withdraw_amount')" sortable width="170">
        </el-table-column>
      <el-table-column prop="balance" :label="$t('pmTransaction.balance')" sortable width="190"></el-table-column> 
      <el-table-column prop="transaction_time" :label="$t('pmTransaction.transaction_time')" sortable width="200"></el-table-column> 
    </el-table> 
    <div class="pagination">
      <el-pagination  @size-change="handleSizeChange" @current-change="handleCurrentChange"
                      :current-page="q.$page" :page-sizes="$store.state.app.pageSizeArr"
                      :page-size="q.$size"
                      layout="total, sizes, prev, pager, next, jumper"
                      :total="listData.total_count">
      </el-pagination>
    </div>
    <show-detail v-if="showDetailInfo" :showDetailInfo.sync ="showDetailInfo" :order_id="order_id"></show-detail>
    <show-match v-if="showMatchInfo" :showMatchInfo.sync ="showMatchInfo" :id="id" :amount="amount"></show-match>
  </div>
</template>

<script>
  import showDetail from './showDetail'
  import showMatch from './matchOrder'
  import { getBankRecordList, getMchList } from '@/api/merchant'
  import {queryFilter} from '@/utils/patch';
  import i18n from '@/lang/index';
  import {isNumeric} from '@/utils/validate';
  import { json2excel } from 'js2excel';
  import { jsonKeyToTitleCase } from '@/utils/index'

  export default {
    components: { showDetail, showMatch },
    data() {
      return {
        listData: {},
        notes: {},
        showDetailInfo: false,
        showMatchInfo: false,
        q: {transaction_time: {}, created_at: {},$size: 30, $page: 1},
        MchList: [],
        MatchStatusArray: ['未匹配', '已匹配'],
        listLoading: true,
        order_id: null,
        id: null,
        amount: null,
        totalExpenses: 0.00,
        totalDeposit: 0.00,
        transfer_from: {$like: ''},
        account_details: null,
        payer: {$like: ''},
        types: { 
          0: 'Deposit',
          1: 'Withdrawal'
        }
      }
    },
    created() {
      this.getList()
      this.getMchList()
    },
    deactivated(){
      this.listLoading = false
    },
    methods: {
      query(){      
        this.q.$page = 1;
        this.getList()
      },
      exportData() {
        this.getList(true)
      },
      reload() {
        this.notes = {}
        this.account_details = '';
        this.q = {transaction_time: {}, created_at: {},$size: 10, $page: 1}
        this.getList()
      },
      sortlist(sort){
        this.q.$orderby = sort.prop
        this.getList()
      },
      handleSizeChange (val) {
        this.q.$size = val
        this.getList()
      },
      handleCurrentChange (val) {
        this.q.$page = val
        this.getList()
      },
      detail(row){
        this.order_id = row.order_id
        this.showDetailInfo = true
      },      
      getTypew(id){
        if(id != null) {
          var trans = 'pmTransaction.types.' + id.toString();          
          return i18n.t(trans);
        } else { 
          return ''; 
        }
      }, 
      match(row){
        this.id = row.id
        this.amount = row.amount
        this.showMatchInfo = true
      },
      getList(isDownload = false) {
        if(this.account_details !== null && this.account_details !== '') {
          let arrAccDetails = this.paresAcctDetail(this.account_details);
          if(arrAccDetails.length > 0) {            
            this.payer.$like = arrAccDetails[0] ? arrAccDetails[0].replace('\t','').replace(' ','') : '';
            this.q.payer = this.payer ? this.payer : '';
            this.transfer_from.$like = arrAccDetails[1] ? arrAccDetails[1].replace(')','').replace(' ','') : '';
            this.q.transfer_from = this.transfer_from ? this.transfer_from : '';
          } else if(!isNumeric(this.account_details)) {
            this.payer.$like = this.account_details;
            this.q.payer = this.payer ? this.payer : '';
          } else {
            this.transfer_from.$like = this.account_details;
            this.q.transfer_from = this.transfer_from ? this.transfer_from : '';
          }           
        }
        if(this.notes.$like) {
          this.q.notes = this.notes
        }
        let params = Object.assign({
          $orderby: '-transaction_time',
          card_type: this.$store.state.app.BankCardType.WITHDRAW
        }, this.q)

        if(isDownload){
          params['$size'] = this.listData.total_count
          params['$page'] = 1
        }

        let queryObj = queryFilter(params)
        this.listLoading = true

        getBankRecordList(queryObj).then(res => {
          if (res.status === 0) {
            if(isDownload){
              this.download(res.data.list);
            } else {
              this.listLoading = false
              this.listData = res.data
              this.totalDeposit = this.listData.income ? parseFloat(this.listData.income).toFixed(2) : 0.00;
              this.totalExpenses = this.listData.spend ? parseFloat(this.listData.spend).toFixed(2) : 0.00;
            }
          }
        })
      },
      getMchList(){
        getMchList({$size: -1}).then(res => {
          if (res.status === 0) {
            this.MchList = res.data.list
          }
        })
      },
      paresAcctDetail(detail){
        let arr = [];
        if(detail.indexOf('(')) { 
          arr = detail.split('(')
        }
        return arr;
      },
      download(data){
        this.listLoading = false
        let transactions = [...data]
        let downloadData = transactions.map(item => ({ 
          card_code: item.bankcard_name,
          type: this.getTypew(item.type),
          bank: item.bank,
          details: this.getAccountDetails(item),
          info_details: item.notes,
          channel: item.trading_channel,
          amount: item.amount ? item.amount.toFixed(2) : 0.00,
          transaction_balance: item.balance,
          transaction_time: item.transaction_time
        }));
        var exportData = jsonKeyToTitleCase(downloadData)
            exportData = this.assignTotalValues(exportData)
        json2excel({ data: exportData, name: 'Transactions', formateDate: 'yyyy/mm/dd' })
      },
      getAccountDetails(data) {
        if (data.payer) {
          return data.payer + '(' + (data.transfer_from ? data.transfer_from : data.transfer_to) + ')'
        } else {
          return (data.transfer_from ? data.transfer_from : data.transfer_to)
        }
      },
      assignTotalValues(data) {
        if(data.length > 0) {    
          let extras = { 
              card_code: '',
              type: '',
              bank: '',
              details: '',
              info_details: '',
              channel: '',
              amount: '',
              transaction_balance: '',
              transaction_time: ''
            }
          data.push(extras)
          let totals = { 
              card_code: '',
              type: '',
              bank: '',
              details: '',
              info_details: '',
              channel: 'Total Deposits',
              amount: this.totalDeposit,
              transaction_balance: 'Total Withdrawals',
              transaction_time: this.totalExpenses
            }
          data.push(totals)
          data = jsonKeyToTitleCase(data)
        }
        return data;
      }
    },
    watch: {
      showDetailInfo() {
        if(!this.showDetailInfo){
          this.getList()
        }
      },
      showMatchInfo() {
        if(!this.showMatchInfo){
          this.getList()
        }
      }
    }
  }

  export const enTransactionPmt = {    
      click_filter: 'Click to filter',
      transaction_time: 'Transaction time',
      select_datetime: 'Select date and time',
      creation_datetime: 'Created Time',
      merchant: 'Company', 
      choose: 'Please Choose', 
      matching_status: 'Matching Status', 
      all: 'All',
      bankcard: 'Bankcard',
      bankcard_name: 'Card Code', 
      bankcard_number: 'Bank card no.', 
      bank: 'Bank', 
      amount: 'Amount',
      pay_amount: 'Pay Amount',
      withdraw_amount: 'Withdraw Amount',
      match_orderid: 'Match order ID', 
      payer: 'Payer',
      search: 'Search',
      reset: 'Reset',
      remarks: 'Remarks', 
      order_id: 'Order ID', 
      created_at: 'Create time',
      updated_at: 'Update time',      
      status: 'Status', 
      balance: 'Transaction Balance', 
      transfer_to: 'Transfer to', 
      transfer_from: 'Transfer from',      
      matcheItems: {
        0: 'Unmatched', 
        1: 'Matched'
      },
      types: {
        0: 'Deposit',
        1: 'Withdrawal'
      },
      type: 'Type',
      payee: 'Payee',
      total_expenses: 'Total Withdrawals',
      total_income: 'Total Deposits',
      currency: 'RMB',
      details: 'Info Details',
      account_details: 'Account Details',
      channel: 'Channel'
  }

  export const zhTransactionPmt = {    
      click_filter: '点击筛选',
      transaction_time: '银行到账时间',
      select_datetime: '选择日期时间',
      creation_datetime: '我方到账时间',
      merchant: '公司',
      choose: '请选择',
      matching_status: '匹配状态', 
      all: '所有',
      bankcard: '银行卡', 
      bankcard_name: '银行卡名称', 
      bankcard_number: '银行卡号', 
      bank: '银行', 
      amount: '金额',
      pay_amount: '收入金额',
      withdraw_amount: '支出金额',
      match_orderid: '匹配订单ID',
      payer: '付款人',
      search: '查询',
      reset: '重置',
      remarks: '备注',      
      order_id: '匹配订单号', 
      created_at: '创建时间',
      updated_at: '创建时间',
      status: '匹配状态', 
      balance: '当前余额', 
      transfer_to: '收款方', 
      transfer_from: '付款方',
      matcheItems: {
        0: '未匹配', 
        1: '已匹配'
      },
      types: {
        0: '存款',
        1: '取款'
      },
      payee: '收款人',
      total_expenses: '支出总额',
      total_income: '存款总额',
      currency: '元',
      type: '交易类型',
      details: '信息详情',
      account_details: '帐户详细资料',
      channel: '渠道'
  }
</script>
